class price_self_index:
    def __init__(self,stock_pool,init_point=1,init_price=None):
        self.stock_pool=stock_pool
        self.init_point=init_point
        self.base_price = {}
        self.last_price={}
        self.returns={}
        self.indexs={}
        self.pre_index=self.init_point
        if init_price is not None:
            self.base_price=init_price
        if isinstance(stock_pool,dict):
            self.isweight=True
        else:
            self.isweight=False
    #接受tick数据
    def on_tick(self,t):
        obj=t["obj"]
        self.last_price[obj]=t["lastPrice"]
    #接受bar数据
    def on_bar(self,b):
        obj = b["obj"]
        self.last_price[obj] = b["close"]
    #直接设置批次tick
    def set_ticks(self,ticks):
        if isinstance(ticks,dict):
            for obj in ticks.keys():
                self.last_price[obj]=ticks[obj]["lastPrice"]
        else:
            for t in ticks:
                obj = t["obj"]
                self.last_price[obj] = t["lastPrice"]
    ##直接设置批次bars
    def set_bars(self,bars):
        if isinstance(bars,dict):
            for obj in bars.keys():
                self.last_price[obj] = bars[obj]["close"]
        else:
            for b in bars:
                obj = b["obj"]
                self.last_price[obj] = b["close"]
    #计算指数
    def cal_index(self,d):
        if self.base_price:
            rs=[]
            for obj in self.stock_pool.keys():
                r=0
                if obj in self.base_price.keys():
                    base=self.base_price[obj]
                    if obj in self.last_price.keys():
                        if self.isweight:
                            r=self.stock_pool[obj]*(self.last_price[obj]-base)/base
                        else:
                            r=(self.last_price[obj]-base)/base
                rs.append(r)
            if self.isweight:
                r0=sum(rs)
            else:
                r0=sum(rs)/len(rs)
            net=self.pre_index*(1+r0)
            self.returns[d]=r0
            self.indexs[d] = net
            self.pre_index=net
        else:
            r0=0
            self.returns[d]=r0
            net=self.init_point
            self.indexs[d] = net
            self.pre_index = net
        for obj,v in self.last_price.items():
            self.base_price[obj]=v
        return net,r0
    #获取指数
    def get_index(self,d):
        return self.indexs[d],self.returns[d]